'use strict';
YX.fn.initMapModel = function() {

	$("body").on("click", "#btn-map", this.openMapModel.bind(this))

	$("body").on("click", "#confirm-location", this.sendMapMsg.bind(this))
}

YX.fn.sendMapMsg = function() {
	var that = this
	if($("#lnglat").val() == null || "" == $("#lnglat").val()) {
		alert("请选择位置!")
		return
	}

	//获得title
	new Promise(function(resolve, reject) {
		var lnglatVal = $("#lnglat").val(),
			lng = new Number(lnglatVal.split(",")[0]),
			lat = new Number(lnglatVal.split(",")[1])
		$.ajax({
			type: "get",
			url: API.getMapAdress + lnglatVal,
			async: true,
			success: function(result) {
				resolve(result)
			},
			erroe: function(err) {
				reject(err)
			}
		}).then(function(obj) {
			let title = obj.regeocode.formatted_address || ""
			const geo = {
				lng: lng,
				lat: lat,
				title: title
			}
			var scene = that.crtSessionType,
				to = that.crtSessionAccount
			that.mysdk.sendGeoMessage(scene, to, geo, that.sendMsgDone.bind(that))
			Modal.hide("#map-modal")

			//console.log(obj.regeocode.formatted_address)
		}, function(err) {
			console.log(err)
		});
	})

}

YX.fn.openMapModel = function() {
	$("#map-modal").load("../zdy-view/mapMadel.html", function() {
		Modal.show("#map-modal", function() {

			//创建地图
			var map = new AMap.Map("container", {
				zoom: 12
			});

			//
			AMap.plugin(['AMap.Autocomplete', 'AMap.PlaceSearch', 'AMap.DistrictSearch', 'AMap.CitySearch'], function() {
				//自动获取用户IP，返回当前城市
				var citysearch = new AMap.CitySearch();
				citysearch.getLocalCity(function(status, result) {
					if(status === 'complete' && result.info === 'OK') {
						if(result && result.city && result.bounds) {
							var cityinfo = result.city;
							var citybounds = result.bounds;
							//地图显示当前城市
							$("#currentCity span").html(result.city);
							$(".city-header span").html(result.city);
						}
					} else {
						$("#currentCity span").html("城市");
					}
				});

				var cSOptions = {
					datatype: 'all',
					type: '190103 |190104' //输入提示时限定POI类型
				};
				var citySearch = new AMap.Autocomplete(cSOptions);
				$("#searchCity").keyup(function() {
					citySearch.search($(this).val(), function(status, result) {
						if(result.count > 0) {
							var cityList = "";
							$.each(result.tips, function(i, city) {
								cityList += "<li adcode='" + city.adcode + "'><i class='iconfont icon-search'></i><span>" + city.name + "</span></li>";
							});
							$(".city-search-result").html(cityList);
						}
					});
				});

				//为地图注册click事件获取鼠标点击出的经纬度坐标
				var clickEventListener = map.on('click', function(e) {
					document.getElementById("lnglat").value = e.lnglat.getLng() + ',' + e.lnglat.getLat()
					console.log(e)
					alert("定位完成")
				});

				//行政区划搜索
				$("#currentCity,.city-header i").click(function() {
					$("#currentCity i").toggleClass("icon-subscript");
					$("#currentCity i").toggleClass("icon-superscript");
					$("#map-search-list").toggle();
				});
				//修改当前城市
				$("#map-search-list").on("click", "li", function() {
					map.setCity($(this).attr("adcode"));
					$("#currentCity").click();
					//地图显示当前城市
					$("#currentCity span").html($(this).children("span").html());
					$(".city-header span").html($(this).children("span").html());
					//关闭搜索结果显示框
					$(".city-search-result").html("");
					//清空输入框值
					$(".city-search input").val("");
				});

				//修改地图放大缩小控件
				AMapUI.loadUI([
						'control/BasicControl'
					],
					function(BasicControl, CityPicker) {
						//缩放控件
						map.addControl(new BasicControl.Zoom({
							position: 'RB' //right bottom，右下角
						}));
					});

				//获取去过城市列表
				var districtSearch = new AMap.DistrictSearch({
					level: 'country',
					subdistrict: 2
				});
				//调用查询方法
				districtSearch.search('中国', function(status, result) {
					var cityList = "";
					$.each(result.districtList[0].districtList, function(i, province) {
						if("undefined" != typeof province.districtList) {
							cityList += "<dt>" + province.name + ":</dt><dd>"
							$.each(province.districtList, function(i, city) {
								cityList += "<li adcode='" + city.adcode + "'><span>" + city.name + "</span></li>";
							})
						}
						cityList += "</dd>";
					});
					$(".city-list").html(cityList)
				});

				//构造地点查询类
				var placeSearch1 = new AMap.PlaceSearch({
					pageSize: 5,
					pageIndex: 1,
					map: map,
					panel: "resultList"
				});
				$(".title-text").on("click", "i", function() {
					//设置指定城市搜索
					placeSearch1.setCity($(".city-header span").html());
					//关键字查询
					placeSearch1.search($(this).prev().val());
				});
				//注册监听，当选中某个标记时会触发
				AMap.event.addListener(placeSearch1, "markerClick", function(e) {
					document.getElementById("lnglat").value = e.data.location.lng + ',' + e.data.location.lat;
					placeSearch1.clear();
				});

				var apt = {
					input: tipinput
				};
				var auto = new AMap.Autocomplete(apt);
				//构造地点查询类
				var placeSearch = new AMap.PlaceSearch({
					map: map
				});
				//注册监听，当选中某条记录时会触发
				AMap.event.addListener(auto, "select", function(e) {
					placeSearch.setCity(e.poi.adcode);
					placeSearch.search(e.poi.name);
				});
				//注册监听，当选中某个标记时会触发
				AMap.event.addListener(placeSearch, "markerClick", function(e) {
					document.getElementById("lnglat").value = e.data.location.lng + ',' + e.data.location.lat
				});

				//定位
				//TODO
				map.plugin('AMap.Geolocation', function() {
					geolocation = new AMap.Geolocation({
						GeoLocationFirst: true,
						zoomToAccuracy: true
					});
					map.addControl(geolocation);
					geolocation.getCurrentPosition();
					//返回定位信息
					AMap.event.addListener(geolocation, 'complete', function(result) {
						document.getElementById("lnglat").value = result.position.lng + ',' + result.position.lat
						console.info(result)

					});
					//返回定位出错信息
					AMap.event.addListener(geolocation, 'error', function(result) {
						console.info(result)
					});
				});
			});
		})

	})
}